package cn.tj212.xiaoyin.wechat.controller;

import cn.tj212.xiaoyin.common.storage.QiniuStorage;
import cn.tj212.xiaoyin.core.auth.domain.AuthUser;
import cn.tj212.xiaoyin.core.auth.service.IAuthUserService;
import cn.tj212.xiaoyin.wechat.wxapi.process.WxMemoryCacheClient;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private IAuthUserService authUserService;

    @RequestMapping(value = "/login")
    public ModelAndView login() {
        return new ModelAndView("login");
    }

    @RequestMapping(value = "doLogin")
    public ModelAndView doLogin(AuthUser user, String toUrl, HttpServletRequest request) {
        //如果已经登录过
		/*if(SessionContext.getWxAuthUser(request) != null){
			return new ModelAndView("redirect:/index.html");
		}*/
		AuthUser tmpAuthUser=new AuthUser();
		tmpAuthUser.setUsername(user.getUsername());
		tmpAuthUser.setPassword(user.getPassword());
		tmpAuthUser=authUserService.getByUsernameAndPassword(tmpAuthUser);
		if (null!=tmpAuthUser){

		    //获取当前用户的openId
		    String openId= WxMemoryCacheClient.getOpenId(request.getSession().getId());
            if (StringUtils.isNotEmpty(openId)){
                tmpAuthUser.setOpenId(openId);
                authUserService.updateSelectivity(tmpAuthUser);
            }else{
                //跳转到一个提示必须关注的页面
            }
            //模拟session存储数据
            String sessionId=request.getSession().getId();
            tmpAuthUser.setHeader(QiniuStorage.getUrl(tmpAuthUser.getHeader()));
            return new ModelAndView("redirect:/user/index.html");
        }

        //登录失败
        ModelAndView mv=new ModelAndView("login");
		mv.addObject("errcode",2);
		return mv;
    }
}
